import axios from "axios";
import { BASE_URL } from "./config";

import localCache from "@/utils/cache";

import router from "@/router";

import { Message } from "element-ui";

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

instance.interceptors.request.use(
  (config) => {
    let token = localCache.getCache("token");
    if (token) {
      config.data.auth_token = token;
      // config.data['auth_token'] = token;
    }
    return config;
  },
  (err) => {
    return err;
  }
);

instance.interceptors.response.use(
  (res) => {
    switch (res.data.status) {
      case 202:
        localCache.clearCache();
        router.push("/login");
        const isShowMessage = true;
        if (isShowMessage) {
          Message.warning("登录过期！");
          isShowMessage = false;
        }
        break;
    }
    return res.data;
  },
  (err) => {
    return err;
  }
);

export default instance;
